<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class HAuth extends CI_Controller {
	public function __construct()
	{
        parent::__construct();
		
		$member = $this->session->userdata('user');
		
		$this->memberid=$member['userid'];
		
		
    }
	public function index()
	{
		$this->load->view('hauth/home');
	}

	public function login($provider)
	{
		log_message('debug', "controllers.HAuth.login($provider) called");
		
		try
		{
			log_message('debug', 'controllers.HAuth.login: loading HybridAuthLib');
			$this->load->library('HybridAuthLib');
			
			
			
			if ($this->hybridauthlib->providerEnabled($provider))
			{
				if($_POST)
				{
					$adapter=$this->hybridauthlib->getAdapter($provider);
					//$facebookid= $adapter->config["keys"]["id"];
					$socialuser[$provider]=$_POST;
					//$this->general_model->delete_row('zap_socialsetting',"userid = ".$this->memberid);
					$social=serialize($_POST);
					$updatedata=array($provider=>$social);
					$this->general_model->update("zap_socialsetting",$updatedata,"userid = ".$this->memberid);
			
					$this->session->set_userdata($socialuser);
					
					
					setcookie("fbss_258245517690131", serialize($_POST));
					
					
					
				}
				//echo $provider;
				log_message('debug', "controllers.HAuth.login: service $provider enabled, trying to authenticate.");
				$service = $this->hybridauthlib->authenticate($provider);
				
				if ($service->isUserConnected())
				{
					//print_r($service);
					log_message('debug', 'controller.HAuth.login: user authenticated.');

					$user_profile = $service->getUserProfile();
					//print_r($user_profile);
					log_message('info', 'controllers.HAuth.login: user profile:'.PHP_EOL.print_r($user_profile, TRUE));

					$data['user_profile'] = $user_profile;
					redirect(BASE_URL.'users/socialsettings');
					//$this->load->view('hauth/done',$data);
				}
				else // Cannot authenticate user
				{
					show_error('Cannot authenticate user');
				}
			}
			else // This service is not enabled.
			{
				log_message('error', 'controllers.HAuth.login: This provider is not enabled ('.$provider.')');
				show_404($_SERVER['REQUEST_URI']);
			}
		}
		catch(Exception $e)
		{
			$error = 'Unexpected error';
			//echo $e->getCode();
			switch($e->getCode())
			{
				case 0 : $error = 'Unspecified error.'; break;
				case 1 : $error = 'Hybriauth configuration error.'; break;
				case 2 : $error = 'Provider not properly configured.'; break;
				case 3 : $error = 'Unknown or disabled provider.'; break;
				case 4 : $error = 'Missing provider application credentials.'; break;
				case 5 : log_message('debug', 'controllers.HAuth.login: Authentification failed. The user has canceled the authentication or the provider refused the connection.');
				         //redirect();
				         if (isset($service))
				         {
				         	log_message('debug', 'controllers.HAuth.login: logging out from service.');
				         	$service->logout();
				         }
				         show_error('User has cancelled the authentication or the provider refused the connection.');
				         break;
				case 6 : $error = 'User profile request failed. Most likely the user is not connected to the provider and he should to authenticate again.';
				         break;
				case 7 : $error = 'User not connected to the provider.';
				         break;
			}

			if (isset($service))
			{
				$service->logout();
			}

			log_message('error', 'controllers.HAuth.login: '.$error);
			show_error('Error authenticating user.');
		}
	}
	public function autologin()
	{
		$EMAIL = $_POST['username'];
		$PASSWORD = $_POST['password'];
		$cookie=NULL;
		$a = $this->cURL("https://login.facebook.com/login.php?login_attempt=1",true,null,"email=$EMAIL&pass=$PASSWORD");
		
		/*$cookiedata = array(
			'name'   => 'fbsr_258245517690131',
			'value'  => $a,
			'expire' => '86500'
		);
		
		$this->input->set_cookie($cookiedata); 
		$cookie2 = $this->input->cookie('fbsr_258245517690131',TRUE);*/
		//print_r($cookie2);
		preg_match('%Set-Cookie: ([^;]+);%',$a,$b);
		$c = $this->cURL("https://login.facebook.com/login.php?login_attempt=1",true,$b[1],"email=$EMAIL&pass=$PASSWORD");
		preg_match_all('%Set-Cookie: ([^;]+);%',$c,$d);
		for($i=0;$i<count($d[0]);$i++)
		$cookie.=$d[1][$i].";";
		
		//print_r($cookie);
		/*
		NOW TO JUST OPEN ANOTHER URL EDIT THE FIRST ARGUMENT OF THE FOLLOWING FUNCTION.
		TO SEND SOME DATA EDIT THE LAST ARGUMENT.
		*/
		redirect(BASE_URL.'users/socialsettings');
		//echo $this->cURL("http://www.facebook.com/",null,$cookie,null);
		//echo $this->cURL("https://www.facebook.com/dialog/oauth?client_id=258245517690131&redirect_uri=http://lr-clients.com/zap/index.php%2Fhauth%2Fendpoint%3Fhauth.done%3DFacebook&state=906210635b9dfb38d153a321301acd45&scope=email%2C+user_about_me%2C+user_birthday%2C+user_hometown%2C+user_website%2C+read_stream%2C+offline_access%2C+publish_stream%2C+read_friendlists&display=page",null,$cookie,null);

	}
	public function cURL($url, $header=NULL, $cookie=NULL, $p=NULL)
    {
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_HEADER, $header);
		curl_setopt($ch, CURLOPT_NOBODY, $header);
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
		curl_setopt($ch, CURLOPT_COOKIE, $cookie);
		curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
		if ($p) 
		{
			curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
			curl_setopt($ch, CURLOPT_POST, 1);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $p);
		}
		$result = curl_exec($ch);
		//print_r($result);
		if ($result) 
		{
			return $result;
		} 
		else 
		{
			return curl_error($ch);
		}
		curl_close($ch);
    }
	public function endpoint()
	{

		log_message('debug', 'controllers.HAuth.endpoint called.');
		log_message('info', 'controllers.HAuth.endpoint: $_REQUEST: '.print_r($_REQUEST, TRUE));

		if ($_SERVER['REQUEST_METHOD'] === 'GET')
		{
			log_message('debug', 'controllers.HAuth.endpoint: the request method is GET, copying REQUEST array into GET array.');
			$_GET = $_REQUEST;
			//print_r($_REQUEST);
		}
		
		log_message('debug', 'controllers.HAuth.endpoint: loading the original HybridAuth endpoint script.');
		require_once APPPATH.'/third_party/hybridauth/index.php';

	}
	public function logout($provider)
	{
		try{
			$this->load->library('HybridAuthLib');
	 
			// call back the requested provider adapter instance 
			$adapter = $this->hybridauthlib->getAdapter($provider);

			// logout the user from $provider
			$adapter->logout(); 

			// return to login page
			redirect(BASE_URL.'users/socialsettings');
		}
		catch( Exception $e ){
			// Display the recived error, 
			// to know more please refer to Exceptions handling section on the userguide
			switch( $e->getCode() ){ 
				case 0 : echo "Unspecified error."; break;
				case 1 : echo "Hybriauth configuration error."; break;
				case 2 : echo "Provider not properly configured."; break;
				case 3 : echo "Unknown or disabled provider."; break;
				case 4 : echo "Missing provider application credentials."; break; 
			} 

			echo "<br /><br /><b>Original error message:</b> " . $e->getMessage();

			echo "<hr /><h3>Trace</h3> <pre>" . $e->getTraceAsString() . "</pre>"; 
		}
	}
}

/* End of file hauth.php */
/* Location: ./application/controllers/hauth.php */
